<template>
  <div class="student-management-container">
    <el-card class="box-card">
      <div class="header">
        <h2 class="title">学生管理</h2>
        <div class="actions">
          <el-button type="primary" @click="refreshStudents" :icon="Refresh" :loading="loading">
            刷新
          </el-button>
        </div>
      </div>

      <div class="student-list">
        <el-table
          :data="paginatedStudents"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无学生数据"
        >
          <el-table-column prop="id" label="学号" width="120" />
          <el-table-column prop="stuName" label="姓名" width="150">
            <template #default="{row}">
              <span class="student-name">{{ row.stuName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stuStudyTime" label="学习时长(分钟)" width="160" />
          <el-table-column prop="stuScore" label="积分" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="200">
            <template #default="{row}">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{row}">
              <el-button type="primary" size="small" @click="viewStudentDetail(row.id)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[15, 30, 50, 100]"
            :small="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="students.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 学生详情对话框 -->
    <el-dialog 
      v-model="showDetailDialog" 
      title="学生详细信息" 
      width="80%"
      class="student-detail-dialog"
    >
      <div v-if="selectedStudent" class="student-detail">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">{{ selectedStudent.id }}</el-descriptions-item>
          <el-descriptions-item label="姓名">
            <span class="detail-name">{{ selectedStudent.stuName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="学习时长">{{ selectedStudent.stuStudyTime }}分钟</el-descriptions-item>
          <el-descriptions-item label="积分">{{ selectedStudent.stuScore }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedStudent.createTime) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 班级信息 -->
        <h3 class="section-title">所属班级</h3>
        <el-table 
          :data="selectedStudent.classes" 
          border 
          style="width: 100%"
          :row-key="row => row.classId"
          v-if="selectedStudent.classes && selectedStudent.classes.length"
        >
          <el-table-column prop="classId" label="班级ID" width="120" />
          <el-table-column prop="className" label="班级名称" />
        </el-table>
        <el-empty v-else description="暂无班级信息" />

        <!-- 课程进度 -->
        <h3 class="section-title">课程进度</h3>
        <el-table 
          :data="selectedStudent.courseProgresses" 
          border 
          style="width: 100%"
          v-if="selectedStudent.courseProgresses && selectedStudent.courseProgresses.length"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="课程名称" width="180">
            <template #default="{row}">
              {{ getCourseName(row.courseId) || `课程ID: ${row.courseId}` }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="章节" width="150">
            <template #default="{row}">
              {{ getChapterName(row.chapterId) || `章节ID: ${row.chapterId}` }}
            </template>
          </el-table-column>-->
          <el-table-column label="学习状态" width="120">
            <template #default="{row}">
              <el-tag :type="row.learnedStatus === 1 ? 'success' : 'warning'">
                {{ row.learnedStatus === 1 ? '已完成' : '进行中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="学习时长" width="140">
            <template #default="{row}">
              {{ Math.floor(row.learnedDuration / 60) }}分钟
            </template>
          </el-table-column>
          <el-table-column label="媒体进度" width="140">
            <template #default="{row}">
              {{ Math.floor((row.mediaProgress / row.mediaDuration) * 100) }}%
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{row}">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无课程进度信息" />

        <!-- 课程评价 -->
        <h3 class="section-title">课程评价</h3>
        <el-table 
          :data="selectedStudent.courseAppraises" 
          border 
          style="width: 100%"
          v-if="selectedStudent.courseAppraises && selectedStudent.courseAppraises.length"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="课程名称" width="180">
            <template #default="{row}">
              {{ getCourseName(row.courseId) || `课程ID: ${row.courseId}` }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="评分" width="140">
            <template #default="{row}">
              <el-rate v-model="row.score" disabled show-score />
            </template>
          </el-table-column>
          <el-table-column prop="content" label="评价内容" />
          <el-table-column prop="createTime" label="评价时间" width="180">
            <template #default="{row}">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无课程评价信息" />
      </div>
      <div v-else>
        <el-empty description="正在加载学生信息..." />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElRate } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { studentApi } from '@/api/students'
import dayjs from 'dayjs'

const loading = ref(false)
const students = ref([])
const currentPage = ref(1)
const pageSize = ref(15)  // 修改为每页15条记录
const showDetailDialog = ref(false)
const selectedStudent = ref(null)
const courseMap = ref({})
const chapterMap = ref({})

// 计算分页后的学生数据
const paginatedStudents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return students.value.slice(start, end)
})

// 时间格式化
const formatDate = (dateString) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm') : '未知时间'
}

// 获取课程名称
const getCourseName = (courseId) => {
  return courseMap.value[courseId] || null
}

// 获取章节名称
const getChapterName = (chapterId) => {
  return chapterMap.value[chapterId] || null
}

// 获取学生列表
const fetchStudents = async () => {
  try {
    loading.value = true
    const response = await studentApi.getAllStudents()
    students.value = Array.isArray(response.data) ? response.data : response
  } catch (error) {
    ElMessage.error('获取学生列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查看学生详情
const viewStudentDetail = async (studentId) => {
  try {
    loading.value = true
    const response = await studentApi.getStudentDetailById(studentId)
    const responseData = response.data || response
    
    selectedStudent.value = {
      ...responseData,
      classes: responseData.classes || [],
      courseProgresses: responseData.courseProgresses || [],
      courseCollections: responseData.courseCollections || [],
      courseAppraises: (responseData.courseAppraises || []).map(a => ({
        ...a,
        score: Number(a.score) || 0
      }))
    }
    
    // 获取课程和章节名称
    await fetchCourseNames()
    showDetailDialog.value = true
  } catch (error) {
    ElMessage.error('获取学生详情失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 获取课程名称映射
const fetchCourseNames = async () => {
  try {
    // 收集所有课程ID
    const courseIds = new Set()
    if (selectedStudent.value.courseProgresses) {
      selectedStudent.value.courseProgresses.forEach(item => {
        if (item.courseId) courseIds.add(item.courseId)
      })
    }
    if (selectedStudent.value.courseCollections) {
      selectedStudent.value.courseCollections.forEach(item => {
        if (item.courseId) courseIds.add(item.courseId)
      })
    }
    if (selectedStudent.value.courseAppraises) {
      selectedStudent.value.courseAppraises.forEach(item => {
        if (item.courseId) courseIds.add(item.courseId)
      })
    }

    // 调用API获取课程名称
    if (courseIds.size > 0) {
      const response = await studentApi.getCourseNamesByIds(Array.from(courseIds))
      courseMap.value = response.data || response
    }
  } catch (error) {
    ElMessage.error('获取课程名称失败: ' + error.message)
  }
}

// 刷新学生列表
const refreshStudents = () => {
  currentPage.value = 1
  fetchStudents()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(fetchStudents)
</script>

<style scoped>
.student-management-container {
  padding: 20px;
  font-size: 16px; /* 增大整体字体大小 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 20px; /* 增大标题字体大小 */
  font-weight: bold;
}

.actions {
  display: flex;
  gap: 10px;
}

.student-list {
  min-height: 500px;
}

.student-name {
  font-weight: bold; /* 姓名加粗 */
  font-size: 16px; /* 增大姓名字体大小 */
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.student-detail {
  padding: 10px;
  max-height: 70vh;
  overflow-y: auto;
  font-size: 16px; /* 增大详情对话框字体大小 */
}

.detail-name {
  font-weight: bold; /* 详情中的姓名加粗 */
  font-size: 18px; /* 增大详情中的姓名字体大小 */
}

.section-title {
  margin: 20px 0 10px;
  font-size: 18px; /* 增大章节标题字体大小 */
  font-weight: bold;
  color: #333;
}

.student-detail-dialog .el-dialog__body {
  padding: 20px;
}

/* 增大表格内容字体大小 */
.el-table {
  font-size: 15px;
}

/* 增大按钮字体大小 */
.el-button {
  font-size: 15px;
}

/* 增大分页组件字体大小 */
.el-pagination {
  font-size: 15px;
}
</style>